<template>
  <view class="min-h-screen bg-gray-50">
    <!-- 自定义导航栏 -->
    <view class="bg-blue-500 px-[32rpx] py-[24rpx] flex items-center">
      <view class="w-[48rpx] h-[48rpx] flex items-center justify-center mr-[24rpx]" @tap="goBack">
        <text class="text-[32rpx] text-white">‹</text>
      </view>
      <text class="text-[36rpx] font-bold text-white flex-1 text-center">收入明细</text>
      <view class="w-[48rpx]"></view>
    </view>

    <!-- 收入统计卡片 -->
    <view class="bg-gradient-to-r from-blue-400 to-blue-600 px-[32rpx] py-[40rpx]">
      <view class="bg-white bg-opacity-20 rounded-[24rpx] p-[32rpx]">
        <view class="text-center mb-[32rpx]">
          <text class="text-[24rpx] text-blue-100 block mb-[8rpx]">今日收入</text>
          <text class="text-[48rpx] font-bold text-white">¥{{ todayEarnings.toFixed(2) }}</text>
        </view>
        
        <view class="grid grid-cols-3 gap-[24rpx]">
          <view class="text-center">
            <text class="text-[32rpx] font-bold text-white block">{{ todayStats.orders }}</text>
            <text class="text-[22rpx] text-blue-100">订单数</text>
          </view>
          <view class="text-center">
            <text class="text-[32rpx] font-bold text-white block">¥{{ todayStats.avgEarning.toFixed(0) }}</text>
            <text class="text-[22rpx] text-blue-100">单均收入</text>
          </view>
          <view class="text-center">
            <text class="text-[32rpx] font-bold text-white block">{{ todayStats.workHours }}h</text>
            <text class="text-[22rpx] text-blue-100">工作时长</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 时间筛选 -->
    <view class="bg-white px-[32rpx] py-[24rpx] mt-[20rpx]">
      <view class="flex items-center justify-between">
        <text class="text-[32rpx] font-bold text-gray-800">收入记录</text>
        <view class="flex items-center">
          <nut-button 
            v-for="filter in timeFilters" 
            :key="filter.key"
            :type="activeFilter === filter.key ? 'primary' : 'default'"
            size="small"
            class="mr-[16rpx] last:mr-0"
            :class="activeFilter === filter.key ? 'bg-blue-500 border-blue-500' : ''"
            @click="changeTimeFilter(filter.key)"
          >
            {{ filter.label }}
          </nut-button>
        </view>
      </view>
    </view>

    <!-- 收入明细列表 -->
    <view class="px-[32rpx] py-[24rpx]">
      <view v-if="filteredEarnings.length === 0" class="text-center py-[120rpx]">
        <text class="text-[32rpx] text-gray-500">暂无收入记录</text>
      </view>
      
      <view v-else class="space-y-[16rpx]">
        <view 
          v-for="earning in filteredEarnings" 
          :key="earning.id"
          class="bg-white rounded-[16rpx] p-[24rpx]"
          @tap="viewEarningDetail(earning)"
        >
          <view class="flex justify-between items-start mb-[16rpx]">
            <view class="flex-1">
              <text class="text-[30rpx] font-medium text-gray-800 block mb-[8rpx]">
                订单 #{{ earning.orderNo }}
              </text>
              <text class="text-[26rpx] text-gray-500">{{ earning.time }}</text>
            </view>
            <view class="text-right">
              <text class="text-[32rpx] font-bold text-green-600">+¥{{ earning.amount.toFixed(2) }}</text>
              <text class="text-[24rpx] text-gray-500 block mt-[4rpx]">{{ earning.type }}</text>
            </view>
          </view>
          
          <view class="flex items-center justify-between pt-[16rpx] border-t border-gray-100">
            <view class="flex items-center">
              <text class="text-[24rpx] text-gray-500 mr-[24rpx]">配送距离: {{ earning.distance }}km</text>
              <text class="text-[24rpx] text-gray-500">用时: {{ earning.duration }}分钟</text>
            </view>
            <text class="text-[24rpx] text-gray-400">›</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 月度统计 -->
    <view class="bg-white px-[32rpx] py-[32rpx] mt-[20rpx] mb-[32rpx]">
      <text class="text-[32rpx] font-bold text-gray-800 block mb-[24rpx]">本月统计</text>
      
      <view class="grid grid-cols-2 gap-[24rpx]">
        <view class="text-center p-[24rpx] bg-gray-50 rounded-[16rpx]">
          <text class="text-[36rpx] font-bold text-gray-800 block">¥{{ monthlyStats.totalEarnings.toFixed(2) }}</text>
          <text class="text-[26rpx] text-gray-500">总收入</text>
        </view>
        <view class="text-center p-[24rpx] bg-gray-50 rounded-[16rpx]">
          <text class="text-[36rpx] font-bold text-gray-800 block">{{ monthlyStats.totalOrders }}</text>
          <text class="text-[26rpx] text-gray-500">完成订单</text>
        </view>
        <view class="text-center p-[24rpx] bg-gray-50 rounded-[16rpx]">
          <text class="text-[36rpx] font-bold text-gray-800 block">{{ monthlyStats.workDays }}</text>
          <text class="text-[26rpx] text-gray-500">工作天数</text>
        </view>
        <view class="text-center p-[24rpx] bg-gray-50 rounded-[16rpx]">
          <text class="text-[36rpx] font-bold text-gray-800 block">¥{{ monthlyStats.avgDaily.toFixed(0) }}</text>
          <text class="text-[26rpx] text-gray-500">日均收入</text>
        </view>
      </view>
    </view>

    <!-- 底部安全区域 -->
    <view class="h-[120rpx]"></view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Taro from '@tarojs/taro'

/**
 * 骑手收入明细页面 - 收入统计和明细记录
 * 性能优化：分页加载收入记录，缓存统计数据
 */

interface EarningRecord {
  id: number
  orderNo: string
  amount: number
  type: '配送费' | '小费' | '奖励'
  time: string
  distance: number
  duration: number
  customerRating?: number
}

interface TimeFilter {
  key: string
  label: string
}

interface TodayStats {
  orders: number
  avgEarning: number
  workHours: number
}

interface MonthlyStats {
  totalEarnings: number
  totalOrders: number
  workDays: number
  avgDaily: number
}

// 响应式数据
const activeFilter = ref('today')

// 计算今日收入总计
const todayEarnings = computed(() => {
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  
  return earningRecords.value
    .filter(record => {
      const recordDate = new Date(record.time)
      return recordDate.toDateString() === today.toDateString()
    })
    .reduce((total, record) => total + record.amount, 0)
})

// 今日统计
const todayStats = computed(() => {
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  
  const todayRecords = earningRecords.value.filter(record => {
    const recordDate = new Date(record.time)
    return recordDate.toDateString() === today.toDateString()
  })
  
  const orders = todayRecords.length
  const avgEarning = orders > 0 ? todayEarnings.value / orders : 0
  
  return {
    orders,
    avgEarning,
    workHours: 8
  }
})

// 月度统计
const monthlyStats = ref<MonthlyStats>({
  totalEarnings: 8560,
  totalOrders: 420,
  workDays: 22,
  avgDaily: 389
})

// 时间筛选选项
const timeFilters = ref<TimeFilter[]>([
  { key: 'today', label: '今日' },
  { key: 'week', label: '本周' },
  { key: 'month', label: '本月' }
])

// 获取当前日期用于生成模拟数据
const getCurrentDate = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const date = String(now.getDate()).padStart(2, '0')
  return { year, month, date, today: `${year}-${month}-${date}` }
}

const { year, month, date, today } = getCurrentDate()
const yesterday = new Date()
yesterday.setDate(yesterday.getDate() - 1)
const yesterdayStr = `${yesterday.getFullYear()}-${String(yesterday.getMonth() + 1).padStart(2, '0')}-${String(yesterday.getDate()).padStart(2, '0')}`

// 收入记录数据
const earningRecords = ref<EarningRecord[]>([
  // 今日收入记录
  {
    id: 1,
    orderNo: `MT${year}${month}${date}0025`,
    amount: 8.5,
    type: '配送费',
    time: `${today} 18:45`,
    distance: 2.3,
    duration: 15,
    customerRating: 5
  },
  {
    id: 2,
    orderNo: `MT${year}${month}${date}0024`,
    amount: 12.0,
    type: '配送费',
    time: `${today} 18:20`,
    distance: 3.1,
    duration: 18,
    customerRating: 5
  },
  {
    id: 3,
    orderNo: `MT${year}${month}${date}0023`,
    amount: 5.0,
    type: '小费',
    time: `${today} 17:50`,
    distance: 1.8,
    duration: 12,
    customerRating: 5
  },
  {
    id: 4,
    orderNo: `MT${year}${month}${date}0022`,
    amount: 15.0,
    type: '配送费',
    time: `${today} 17:30`,
    distance: 4.2,
    duration: 25,
    customerRating: 4
  },
  {
    id: 5,
    orderNo: `MT${year}${month}${date}0021`,
    amount: 20.0,
    type: '奖励',
    time: `${today} 17:00`,
    distance: 0,
    duration: 0
  },
  {
    id: 6,
    orderNo: `MT${year}${month}${date}0020`,
    amount: 9.5,
    type: '配送费',
    time: `${today} 16:40`,
    distance: 2.8,
    duration: 16,
    customerRating: 5
  },
  {
    id: 7,
    orderNo: `MT${year}${month}${date}0019`,
    amount: 11.0,
    type: '配送费',
    time: `${today} 16:15`,
    distance: 3.5,
    duration: 20,
    customerRating: 4
  },
  {
    id: 8,
    orderNo: `MT${year}${month}${date}0018`,
    amount: 7.5,
    type: '配送费',
    time: `${today} 15:50`,
    distance: 2.1,
    duration: 14,
    customerRating: 5
  },
  {
    id: 9,
    orderNo: `MT${year}${month}${date}0017`,
    amount: 13.5,
    type: '配送费',
    time: `${today} 15:25`,
    distance: 3.8,
    duration: 22,
    customerRating: 5
  },
  {
    id: 10,
    orderNo: `MT${year}${month}${date}0016`,
    amount: 6.0,
    type: '配送费',
    time: `${today} 15:00`,
    distance: 1.5,
    duration: 10,
    customerRating: 4
  },
  {
    id: 11,
    orderNo: `MT${year}${month}${date}0015`,
    amount: 10.0,
    type: '配送费',
    time: `${today} 14:35`,
    distance: 2.9,
    duration: 18,
    customerRating: 5
  },
  {
    id: 12,
    orderNo: `MT${year}${month}${date}0014`,
    amount: 8.0,
    type: '配送费',
    time: `${today} 14:10`,
    distance: 2.4,
    duration: 16,
    customerRating: 5
  },
  {
    id: 13,
    orderNo: `MT${year}${month}${date}0013`,
    amount: 14.5,
    type: '配送费',
    time: `${today} 13:45`,
    distance: 4.1,
    duration: 24,
    customerRating: 4
  },
  {
    id: 14,
    orderNo: `MT${year}${month}${date}0012`,
    amount: 3.0,
    type: '小费',
    time: `${today} 13:20`,
    distance: 1.2,
    duration: 8,
    customerRating: 5
  },
  {
    id: 15,
    orderNo: `MT${year}${month}${date}0011`,
    amount: 16.0,
    type: '配送费',
    time: `${today} 12:55`,
    distance: 4.5,
    duration: 28,
    customerRating: 5
  },
  // 昨日收入记录
  {
    id: 16,
    orderNo: `MT${yesterdayStr.replace(/-/g, '')}0035`,
    amount: 12.5,
    type: '配送费',
    time: `${yesterdayStr} 19:30`,
    distance: 3.2,
    duration: 19,
    customerRating: 5
  },
  {
    id: 17,
    orderNo: `MT${yesterdayStr.replace(/-/g, '')}0034`,
    amount: 8.0,
    type: '配送费',
    time: `${yesterdayStr} 19:05`,
    distance: 2.1,
    duration: 13,
    customerRating: 4
  },
  {
    id: 18,
    orderNo: `MT${yesterdayStr.replace(/-/g, '')}0033`,
    amount: 15.0,
    type: '奖励',
    time: `${yesterdayStr} 18:30`,
    distance: 0,
    duration: 0
  },
  {
    id: 19,
    orderNo: `MT${yesterdayStr.replace(/-/g, '')}0032`,
    amount: 10.5,
    type: '配送费',
    time: `${yesterdayStr} 18:00`,
    distance: 2.8,
    duration: 17,
    customerRating: 5
  },
  {
    id: 20,
    orderNo: `MT${yesterdayStr.replace(/-/g, '')}0031`,
    amount: 7.0,
    type: '配送费',
    time: `${yesterdayStr} 17:35`,
    distance: 1.9,
    duration: 12,
    customerRating: 4
  }
])

// 计算属性
const filteredEarnings = computed(() => {
  // 根据时间筛选条件过滤收入记录
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  
  return earningRecords.value.filter(record => {
    const recordDate = new Date(record.time)
    
    switch (activeFilter.value) {
      case 'today':
        return recordDate.toDateString() === today.toDateString()
      case 'week':
        const weekStart = new Date(today)
        weekStart.setDate(today.getDate() - today.getDay())
        return recordDate >= weekStart
      case 'month':
        const monthStart = new Date(today.getFullYear(), today.getMonth(), 1)
        return recordDate >= monthStart
      default:
        return true
    }
  })
})

// 方法
const goBack = () => {
  Taro.navigateBack()
}

const changeTimeFilter = (filterKey: string) => {
  activeFilter.value = filterKey
}

const viewEarningDetail = (earning: EarningRecord) => {
  console.log('查看收入详情:', earning.orderNo)
  Taro.showModal({
    title: '收入详情',
    content: `订单号: ${earning.orderNo}\n收入: ¥${earning.amount.toFixed(2)}\n类型: ${earning.type}\n配送距离: ${earning.distance}km\n用时: ${earning.duration}分钟${earning.customerRating ? `\n客户评分: ${earning.customerRating}星` : ''}`,
    showCancel: false,
    confirmText: '确定'
  })
}

// 生命周期
onMounted(() => {
  console.log('收入明细页面加载完成')
  console.log('今日收入记录数量:', filteredEarnings.value.length)
  console.log('今日总收入:', todayEarnings.value)
  loadEarningData()
})

const loadEarningData = () => {
  console.log('加载收入数据')
  console.log('全部收入记录数量:', earningRecords.value.length)
  // 实际项目中会从API获取数据
}
</script>

<style lang="scss" scoped>
.bg-gradient-to-r {
  background: linear-gradient(90deg, #60a5fa 0%, #2563eb 100%);
}

.space-y-\[16rpx\] > view:not(:first-child) {
  margin-top: 16rpx;
}

.last\:mr-0:last-child {
  margin-right: 0;
}
</style> 